package conf

import (
	"encoding/json"
	"gopkg.in/yaml.v3"
	"io/fs"
	"os"
	"path/filepath"
)

type fc struct {
	value map[string]interface{}
}

func NewFile() (IClient, error) {
	f := &fc{
		value: make(map[string]interface{}),
	}
	if err := f.load(); err != nil {
		return nil, err
	}
	return f, nil
}

func (f fc) Get(key string) string {
	if v, ok := f.value[key]; ok {
		if s, exist := v.(string); exist {
			return s
		}
	}
	return ""
}

func (f fc) Bind(key string, value interface{}) error {
	if v, ok := f.value[key]; ok {
		if bs, err := json.Marshal(v); err == nil {
			return json.Unmarshal(bs, &value)
		}
	}
	return ErrKeyNotFound
}

func (f *fc) load() error {
	if cfgPath == "" {
		return ErrCfgFileNotFound
	}
	_ = filepath.Walk(cfgPath, func(path string, info fs.FileInfo, err error) error {
		if !info.IsDir() {
			bs, err := os.ReadFile(path)
			if err != nil {
				return err
			}
			if err := yaml.Unmarshal(bs, f.value); err != nil {
				return err
			}
		}
		return nil
	})
	return nil
}
